import { linkTo, cardParams, search, save, refersh, confirmOfModalClick, queryCard, deleteCenterPrise, addOperationCol, empower, structorBoolean, addReq } from "./index.js";
import { vendorsDanger as danger, vendorsWarning as warning } from './../../../utils/config.js';
import { Upload } from 'tinper-bee';

const buttonClickEvents = {
    "Add": addClick,
    "CreateBusiness": createBusinessClick,
    "Edit": addClick,
    "Delete": deleteClick,
    "refresh": refreshClick,
    "Search": searchClick,
    "Clear": clearClick,
    "Save": saveClick,
    "Cancel": cancelClick,
    "InsertRow": insertRowClick,
    "DeleteRow": deleteClick,
    "DeleteRows": deleteClick,
    "Empower": empowerClick,
    "EmpowerRow": empowerClick,
    "UnEmpower": empowerClick,
    "UnEmpowerRow": empowerClick,
    "DownTemplate": downTemplateClick,
    "Back": cancelClick
}


function buttonClick(id, record, index) {
    buttonClickEvents[id].call(this, id, record, index);
}

function addClick(id, record) {
    let {
        status,
        pk
    } = this.state;
    if (id === "Add") {

        status = "add"
        addReq({}).then((response) => {
            if (response.data.result) {
                edit.call(this, status, record, id)
            } else {
                danger({ "text": response.data.exMsg });
            }
        })
    } else if (id === "Edit") {
        status = "edit";
        edit.call(this, status, record, id)
    }

}

function edit(status, record, id) {
    let {
        pk
    } = this.state;

    if (this.props.location.pathname !== "/card") {//列表表体的修改
        linkTo.call(this, "/card", { status: status, pk: record ? record.pkEnterprise : '' })
    } else {//卡片的按钮
        this.setState({
            status: status
        }, () => {
            this.props.form.setFormStatus(status)
            this.props.button.setButtonState(status)
            addOperationCol.call(this)
            if (id === 'Edit' && pk || id === 'Edit' && record.pkEnterprise) {
                queryCard.call(this, { pkEnterprise: pk || record.pkEnterprise })
                //根据主键查询

            } else {
                this.props.form.clearFormValue()
                this.modalTreeC.output.clearSelectDataByDataSouce("personnelFiles_modalOrgTree_form_area")
                this.setState({
                    tableData: [],
                    initData: { tableData: [] },
                })
            }
        })
    }
}

function setButtonDisabled(buttonObj) {

    for (let button in buttonObj) {
        if (document.getElementById(button)) {
            document.getElementById(button).disabled = buttonObj[button];
        }
    }
}

function setButtonVisable(buttonObj) {
    for (let button in buttonObj) {
        if (document.getElementById(button)) {
            document.getElementById(button).style.visibility = "none";
        }
    }
}

function createBusinessClick(id, record) {
    this.modalTreeC.output.isShow("personnelFiles_modalOrgTree_createEnter_area")
}

function refreshClick() {

    let {
        status,
        pk
    } = this.state;

    if (!status) {
        refersh.call(this, {})
    } else if (this.state.status === "browse" && pk) {
        queryCard.call(this, { pkEnterprise: pk }, true)
    }
}

function searchClick(id, record) {
    let rolesA = []
    record.roles.map((item) => {
        rolesA.push(item.key)
    })
    let params = {
        name: record.name,
        roles: rolesA,
        pkOrgs: record.pkSrc,
    }
    search.call(this, params)
}

function clearClick(id) {
    this.setState({
        businessName: '',//企业名称
        businessId: '',
        orgName: '', //组织名称
        orgId: '',
        businessRule: [],//企业角色
        businessRuleId: [],
    })
}

//card page
function saveClick(id, record) {
    let { deleteTableS } = this.state;
    let params = cardParams.call(this);
    let flag = checkout.call(this, "Save", params);

    if (!flag) {
        return;
    }

    //合并删除数据
    let data = structorBoolean.call(this, deleteTableS)
    
    params.personnelVOS = params.personnelVOS.concat(data)
    save.call(this, params)
}

function checkout(type, data) {
    let flag = true
    switch (type) {
        case "Save":
            if (!data.name || !data.role) {
                warning({ "text": `有必输项未填` })
                flag = false
            }
            if (data.personnelVOS.length) {
                data.personnelVOS.map((item, index) => {
                    if (!item.sname) {
                        warning({ "text": `人员名称未填` })

                        flag = false
                        return;
                    }
                    if (!item.phone && !item.email) {
                        warning({ "text": `手机号或邮箱请填写一个` })

                        flag = false
                        return;
                    }
                })
            }
            break;
        default: flag = true;
    }
    return flag
}

function cancelClick(id, record) {
    if (this.state.status === 'browse') {
        linkTo.call(this, "/list")
    } else {
        this.props.promptModal.isShow({
            show: true,
            title: this.state.buttonIdCur === "Add" ? '是否清除当前编辑数据？' : '是否清除数据并退出当前编辑页面？',
            content: this.state.buttonIdCur === "Add" ? '是否清除当前编辑数据？' : '是否清除数据并退出当前编辑页面？',
            confirm: confirmOfModalClick.bind(this),
        })

        this.setState({
            buttonIdCur: id,
            selectedTableData: []
        })
    }

}

function insertRowClick(id, record) {
    let newRow = {
        userName: '',
        sname: '',
        phone: '',
        email: '',
        isContacts: 0,
        isSpecialWork: 0,
        isYgcAuthorizer: 0,
        memo: '',
        index: this.state.tableData.length,
        key: this.state.tableData.length,
    };

    this.state.tableData.push(newRow);
    this.setState({
        tableData: [...this.state.tableData],
    })
}

function empowerClick(id, record) {
    if (this["empower"]) {
        warning({ "text": `当前数据已被修改，请刷新后重试` })
        return;
    }


    if (id === "Empower" || id === "UnEmpower") {
        if (!this.state.selectedTableData.length) {
            warning({ "text": "请先选中人员数据" })
            return
        }
    }
    let params = { onOff: id === "Empower" || id === "EmpowerRow" ? "on" : "off", personnelVOS: [] }

    if (record) {
        params["personnelVOS"] = [record]
    } else {
        let flag = false;

        this.state.selectedTableData.map((item, index) => {
            if ((id === "Empower" || id === "EmpowerRow") && item.isYgcAuthorizer) {
                warning({ text: '当前选中人员中存在已是授权状态或刷新后重试' })
                flag = true;
                return
            } else if ((id === "UnEmpower" || id === "UnEmpowerRow") && !item.isYgcAuthorizer) {
                warning({ text: '当前选中人员中存在已是未授权状态或刷新后重试' })
                flag = true;
                return
            }
        })
        if (flag) {
            return
        }
        params["personnelVOS"] = this.state.selectedTableData
    }


    if (!this["empower"]) {
        this["empower"] = true
    }

    params["personnelVOS"] = structorBoolean.call(this, params["personnelVOS"])
    empower.call(this, params)
}
function downTemplateClick() {
    location.href = 'https://gysy-pmc-pub.oss-cn-beijing.aliyuncs.com/files/%E7%94%A8%E6%88%B7%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls'
}
function deleteClick(id, record, index) {
    let tableData = [...this.state.tableData];
    if (this.state.status) {//卡片
        if (this.state.status === "browse") {
            let params = cardParams.call(this);
            deleteCenterPrise.call(this, [params])
            return
        }

        if (id === 'DeleteRow') {
            if (record.isYgcAuthorizer) {
                warning({ text: '如果删除用户，则先取消授权' })
                return;
            } else if (!record.isYgcAuthorizer && record.pkPersonnel) {
                warning({ text: '删除用户后，该用户的业务数据均保留' })
            }

            this.state.deleteTableS.map((item, innerIndex) => {
                console.log(this.state.tableData[item.index], 666666)
                if (item.pkPersonnel && item.pkPersonnel === this.state.tableData[index].pkPersonnel) {
                    this.state.deleteTableS.splice(innerIndex, 1);
                }
            })

            if (this.state.status === "edit" && this.state.tableData[index].pkPersonnel) {
                this.state.tableData[index]["dr"] = 1;
                this.state.deleteTableS.push(this.state.tableData[index])
            }
            tableData.splice(index, 1);


        } else if (id === 'DeleteRows') {
            if (this.state.selectedTableData.length === 0) {
                warning({ text: '请先选中人员数据，再批量删行！' })
                return;
            }

           

            this.state.selectedTableData.map((item) => {
                if (item.isYgcAuthorizer) {
                    warning({ text: '如果删除用户，则先取消授权' })
                    return;
                } else if (!item.isYgcAuthorizer && item.pkPersonnel) {
                    warning({ text: '删除用户后，该用户的业务数据均保留' })
                }
                
                if (this.state.status === "edit" && this.state.tableData[item.index].pkPersonnel) {
                    this.state.tableData[item.index]["dr"] = 1;
                    this.state.deleteTableS.push(this.state.tableData[item.index])
                }
                let findIndex = tableData.findIndex((itemSelect, indexSelect) => {
                    return itemSelect.index === item.index
                })
                if (findIndex !== -1) {
                    tableData.splice(findIndex, 1);

                }
            })

            this.state.deleteTableS.map((item, deleteIndex) => {
                if (item.pkPersonnel && item.pkPersonnel === tableData.length && tableData[item.index].pkPersonnel) {
                    this.state.deleteTableS.splice(deleteIndex, 1);
                }
            })
        }
        tableData.map((item, index) => {
            item["index"] = index
            item["key"] = index
        })
        this.setState({
            tableData: [...tableData],
            deleteTableS: [... this.state.deleteTableS],
            selectedTableData: []
        })
    } else {//列表
        let data = []
        if (id === 'Delete') {
            data = [...this.state.selectedTableData]
            if (!data.length) {
                warning({ "text": "请先选中数据" })
            }

        } else if ((id === 'DeleteRow')) {
            data = [record]
        }

        if (data.length) {
            data = structorBoolean.call(this, data)
            deleteCenterPrise.call(this, data)
        }
    }

}
function onRowDoubleClick(record, index, event) {
    linkTo.call(this, "/card", { status: "browse", pk: record.pkEnterprise, record: record })
}

export {
    buttonClick,
    onRowDoubleClick,
    setButtonDisabled,
    setButtonVisable,
    empowerClick
}